package com.shed.demo.dwr;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.directwebremoting.WebContextFactory;

import com.shed.demo.domain.User;

public class DwrAuthHelper {
	/**
	 * The session key
	 */
	private static final String USER = "com.shed.demo.USER";
	private static final String LOGINID = "com.shed.demo.LOGINID";
	private static final String LOGINIP = "com.shed.demo.LOGINIP";

	/**
	 * 设置当前session用户,用于系统登录
	 * 
	 * @param user
	 *            当前session用户
	 */
	public static void setUser(Object user) {
		HttpSession session = WebContextFactory.get().getSession(true);
		session.setAttribute(USER, user);
		session.setAttribute(LOGINID, ((User) user).getUserID());
		session.setAttribute(LOGINIP, WebContextFactory.get().getHttpServletRequest().getRemoteAddr());
	}

	/**
	 * 获取当前session用户
	 * 
	 * @return 当前session用户
	 */
	public static Object getUser() {
		HttpSession session = WebContextFactory.get().getSession(true);
		return session.getAttribute(USER);
	}

	/**
	 * 获取当前session ID
	 * 
	 * @return
	 */
	public static String getSessionId() {
		HttpSession session = WebContextFactory.get().getSession(true);
		return session.getId();
	}

	/**
	 * 清除当前session用户
	 */
	public static void removeUser() {
		HttpSession session = WebContextFactory.get().getSession(true);
		session.removeAttribute(USER);
	}

	/**
	 * 获取远程用户ipaddress
	 */
	public static String getIpAddress() {
		HttpServletRequest request = WebContextFactory.get().getHttpServletRequest();
		String ip = request.getHeader("x-forwarded-for");
		if (ip != null) {
			String[] ips = ip.split(",");
			for (String o : ips) {
				if (!o.equals("unknown")) {
					return o;
				}
			}
		} else {
			ip = request.getRemoteAddr();
		}
		return ip;
	}
}
